package com.cc.secondKill.rabbit;

import com.cc.secondKill.commnons.JsonUtils;
import com.cc.secondKill.commnons.ShardedJedisPoolUtils;
import com.cc.secondKill.dao.GoodsMapper;
import com.cc.secondKill.dao.OrderMapper;
import com.cc.secondKill.pojo.Goods;
import com.cc.secondKill.pojo.MiaoshaMessage;
import com.cc.secondKill.pojo.Order;
import com.cc.secondKill.service.impl.GoodsService;
import com.cc.secondKill.service.impl.OrderService;
import com.mysql.jdbc.PreparedStatement;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class MQReceiver implements ChannelAwareMessageListener{

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;

    private static Logger logger = LoggerFactory.getLogger(MQReceiver.class);


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void onMessage(Message message ,Channel channel) throws Exception {
        String str = null;
        try {
            str = new String(message.getBody(),"utf-8");
        }catch (Exception e){
            logger.error("获取消息内容异常",e);
            e.printStackTrace();
        }
        logger.info("收到消息:{}",str);
//        QueueingConsumer consumer = new QueueingConsumer(channel);
//        channel.basicConsume("queueTest",false,consumer);
        MiaoshaMessage miaoshaMessage = JsonUtils.String2Obj(str,MiaoshaMessage.class);
        String phone = miaoshaMessage.getUserPhone();
        Integer goodsId = miaoshaMessage.getGoodsId();
        Goods goods = this.goodsMapper.selectByPrimaryKey(goodsId);
        if (goods.getStock() <= 0){
            return;
        }
        Order order = this.orderService.getOrderByGoodsIdAndPhone(phone,goodsId);
        if (order != null){
            return;
        }
        Goods updateGoods = new Goods();
        updateGoods.setId(goodsId);
        updateGoods.setStock(goods.getStock()-1);
        Integer rows = this.goodsMapper.updateByPrimaryKeySelective(updateGoods);
        if (rows > 0){
            //下订单
            Order msOrder = new Order();
            msOrder.setGoodsId(goodsId);
            msOrder.setName("cc");
            msOrder.setPhone(phone);
            Integer rowsCount = this.orderMapper.insert(msOrder);
        }
        //channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
